package fr.tocchisu.movies.services.db.mongoDB;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

import fr.tocchisu.movies.services.Movie;
import fr.tocchisu.movies.services.parsers.PlainTextMovieInterfaceParser;

public class MovieDBInit extends PlainTextMovieInterfaceParser {
    private final static Logger LOGGER = LoggerFactory.getLogger(MovieDBInit.class);

    private DB db;
    private DBCollection dbCollection;
    private final String hostname = "localhost";
    private final String dbName = "test";
    private String username;
    private String pwd;
    private int port;
    private final Map<String, Object> keyvalues = new HashMap<String, Object>();

    @Override
    protected void beforeFileParsed() {
	Mongo mongo = null;
	try {
	    mongo = new Mongo(hostname);
	} catch (Exception e) {
	    LOGGER.error(e.getMessage(), e);
	}
	db = mongo.getDB(dbName);
	if (StringUtils.isNotBlank(username))
	    db.authenticate(username, pwd.toCharArray());
	dbCollection = db.getCollection("movies");
	dbCollection.drop();
	DBObject keys = new BasicDBObject();
	keys.put("name", 1);
	keys.put("releaseDate", 1);
	dbCollection.createIndex(keys);

    }

    @Override
    public void afterLineParsed(Movie movie) {
	DBObject basicDBObject = new BasicDBObject();
	try {
	    basicDBObject.putAll(BeanUtils.describe(movie));
	} catch (Exception e) {
	    LOGGER.error(e.getMessage(), e);
	}
	dbCollection.insert(basicDBObject);
    }

    @Override
    protected void afterFileParsed() {
	db.getMongo().close();
    }

    public static void main(String[] args) {
	// try {
	// System.out.println("Please enter a hostname :");
	// System.in.read();
	// System.out.println();
	// System.out.println("Please enter a dbname :");
	// System.in.read();
	new MovieDBInit().read();
	// } catch (IOException e) {
	// LOGGER.error(e.getMessage(), e);
	// }
    }
}
